define(['./data'],function(kit,DATA){
    function type(t){
        switch(t){
            case 1:
                return "ios";
            case 2:
                return "Android";
            case 3:
                return "ipad";
        }
    }

    function Parse(){
        var self = this;
        /**
        ** /cache/newProduct    返回的结果  step2  会调用这个接口
        **/
        this.cache = function(raw){

            if(typeof(raw)=="string") raw = JSON.parse(raw);//先对象化数据
            DATA.cache = raw.data;//缓存池中的数据，如果是新建，应该大部分为空
            var initSetting = DATA.cache.adPublishConditionDetailCache;//初始化的固定数据
            //将投放控制的性别，转为用户定位之性别
            this.processGender(initSetting.sex);

            DATA.sessionData.cache = JSON.stringify(DATA.cache);
            DATA.temp = {Platform:initSetting.platform,
                         Age:[initSetting.age],
                         Location:[{countries:[],cities:[],locationType:1}],
                         CustomAudience:[{}],
                         LookalikeAudience:[],
                         Gender:[[DATA.Gender.DefaultGender]],
                         PageTypes:[[0]],
                         WirelessConnection:[[0]],
                         Interests:[[]],//{id:"",name:"",locale:"en_US"}
                         Behavior:[[]],
                         CollegeYears:[{}],
                         Connections:[{type:0,connections:[{id:DATA.app.fbConnectionObjectId,name:DATA.app.name}]}],//[{"type":0,"connections":[{"id":"40","name":"Fantasy Of Elements"}]}]
                         EducationMajors:[[]],
                         EducationSchools:[[]],
                         EducationStatuses:[[]],
                         EthnicAffinity:[[]],
                         FamilyStatuses:[[]],
                         Generation:[[]],
                         Industries:[[]],
                         Languages:[[]],
                         LifeEvents:[[]],
                         NewInterestedIn:[[]],
                         NewRelationshipStatus:[[]],
                         Politics:[[]],
                         WorkEmployers:[[]],
                         WorkPositions:[[]]
                        };

            //默认用的是第一个模板，走data.js 里面的默认
            DATA.sessionData.temp = JSON.stringify(DATA.temp);//存储默认选中的第一个模板
            DATA.nowTemp = JSON.parse(DATA.sessionData.temp);

            DATA.userTemp = {"userAudienceTemplateId":-1,
                          "fbConnectionObjectId":DATA.app.fbConnectionObjectId,
                          "productConfId":DATA.prod.id,
                         "userAudienceTemplates":
                             [
                                 {
                                     id: '-1',
                                     name: I18N.getText('createAd', 'userAudienceType'),
                                     children: [
                                         { id: '-1', name: I18N.getText('createAd', 'newUserAudience') ,templateTargetingSpecs:JSON.stringify(DATA.temp)}

                                     ]
                                 },
                                 {
                                     id: '-2',
                                     name: I18N.getText('createAd', 'userAudienceTmpl'),
                                     children: [
                                     ]
                                 }
                             ]
                             // [{id:-1,name:"新用户定位",templateTargetingSpecs:JSON.stringify(DATA.temp)}]
            };
            if (window.sessionStorage.roleId.indexOf(13) > -1) {
                var aaaa = { id: '-2', name: I18N.getText('createAd', 'customAudience') ,templateTargetingSpecs:JSON.stringify(DATA.temp)};
                var bbbb = { id: '-3', name: I18N.getText('createAd', 'lookalikeAudience'), templateTargetingSpecs:JSON.stringify(DATA.temp) };
                DATA.userTemp.userAudienceTemplates[0].children.push(aaaa);
                DATA.userTemp.userAudienceTemplates[0].children.push(bbbb);
            }

            //用户定位的模板
            DATA.userTemp.userAudienceTemplates[1].children = DATA.cache.userAudienceTemplate.userAudienceTemplates;
            DATA.sessionData.userTemp = JSON.stringify(DATA.userTemp);//存储模板列表
            DATA.sessionData.tempIndex = JSON.parse(DATA.tempIndex);

            DATA.aca = DATA.cache.accountCustomAudiences; //自定义受众的 选择账号,【常数】

            DATA.sessionData.aca = JSON.stringify(DATA.aca);//存储默认选中的第一个模板 【常数】

            DATA.pageList = DATA.cache.pageList;
            DATA.sessionData.pageList = JSON.stringify(DATA.pageList);

            DATA.adTitle = DATA.cache.adPublishInputHistoryCache.connectionObjectName;//默认标题
            DATA.sessionData.adTitle = JSON.stringify(DATA.adTitle);
            DATA.page = DATA.pageList[0];
            DATA.sessionData.page = JSON.stringify(DATA.page);

            DATA.radio = DATA.cache.radio;
            DATA.sessionData.radio = JSON.stringify(DATA.radio);

            DATA.adCampSeq = DATA.cache.adCampSeq;
            DATA.adSetSeq = DATA.cache.adSetSeq,
            DATA.adGroupSeq = DATA.cache.adGroupSeq

            self.aim(DATA.cache);
            self.price(DATA.cache);
            self.innovate(DATA.cache);
            self.naming(DATA.cache);
        }

        /**
        **从保存过的模板里面取数据
        **
        */
        function aim_saved(raw){
            var saved = JSON.parse(raw.templateTargetingSpecs);
            DATA.temp = saved;//当前模板是哪个
            DATA.tempIndex = raw.id;
            DATA.sessionData.tempIndex = JSON.stringify(DATA.tempIndex);//存选中的模板
            DATA.nowTemp = JSON.parse(raw.templateTargetingSpecs);
            DATA.sessionData.temp = JSON.stringify(DATA.temp);//存选中的模板

            //根据广告发布条件 修改模板中的性别数据
            var genders = [];
            var tempGenders = DATA.temp.Gender;
            var index = 0;
            $.each(tempGenders, function(i, tempGender){
                var temp;
                if (0 == tempGender.length){
                    temp = 0;
                } else {
                    temp = tempGender[0];
                }

                if (DATA.Gender.GenderRenders[temp]){
                    genders[index] = tempGender;
                    index++;
                }
            });
            if (0 == genders.length){
                //如果模板中无满足条件的性别，则给一个默认值
                genders[0] = [DATA.Gender.DefaultGender]
            }
            DATA.temp.Gender = genders;
            DATA.nowTemp.Gender = genders;

            //过滤有效的兴趣
            if(saved.Interests && saved.Interests.length > 0){
                var InterestValid = [];
                $.each(saved.Interests,function(idx,v){
                    InterestValid = InterestValid.concat(v);
                });
                DATA.filterValidInterest(InterestValid,function(err,data){
                    var ValidInterests = [],ValidedIds = kit.ids(data);
                    if(err){
                        console.log(err);
                    } else{
                        $.each(saved.Interests,function(filter_idx,filter_Interests){
                            var tmpInterest = [];
                            $.each(filter_Interests,function(idx,v){
                                for(var tmpi = 0, length = data.length; tmpi < length ; tmpi++ ){
                                    if(data[tmpi].id == v.id){
                                        tmpInterest.push(v)
                                    }
                                }
                            })
                            ValidInterests.push(tmpInterest);
                        })
                        saved.Interests = ValidInterests;
                    }
                })
            }

            DATA.temp.Interests = saved.Interests;
            DATA.nowTemp.Interests = saved.Interests;
        }

        //用户定位  这一项目  , 使用已经保存过的模板还是，新模板
        this.aim = function(raw){
            if(raw.templateTargetingSpecs) aim_saved(raw);
        };
        //广告创意
        this.innovate = function(raw){
            DATA.adWords = raw.adWords||[""];
            raw.adWords = DATA.adWords;

            DATA.adTitleList = raw.adPublishInputHistoryCache.adTitleHistoryList;
            if (!DATA.adTitleList || 0 == DATA.adTitleList.length){
                //如果没有历史标题 则用应用名作为标题
                DATA.adTitleList = [];
                DATA.adTitleList.push({
                    id: -1,
                    text: DATA.app.name,
                    title: DATA.app.name
                });
            } else {
                var appTitle = null;
                $.each(DATA.adTitleList, function(i, _historyAdTitle){
                    if (_historyAdTitle.title == DATA.app.name){
                        appTitle = _historyAdTitle;
                    }
                });

                if (null != appTitle){
                    //如果历史标题中有应用名称
                    appTitle.id = -1;
                } else {
                    //如果历史标题中无应用名称
                    DATA.adTitleList.push({
                        id: -1,
                        text: DATA.app.name,
                        title: DATA.app.name
                    });
                }
            }

            DATA.sessionData.adTitleList = JSON.stringify(DATA.adTitleList);//存储默认选中的第一个模板

            DATA.pageList = raw.pageList;
            DATA.sessionData.pageList = JSON.stringify(raw.pageList);

            DATA.sessionData.cache = JSON.stringify(DATA.cache);//广告词

            DATA.actionOption = {text: "立即安装", value: "INSTALL_MOBILE_APP", id: 7};
            DATA.sessionData.actionOption = JSON.stringify(DATA.actionOption);

        }
        //广告命名
        this.naming = function(raw){
            DATA.tagNames = raw.tagNames;
            DATA.adSetSeq = raw.adSetSeq;//广告营销名称
            DATA.adCampSeq = raw.adCampSeq;//系列名称
            DATA.entrustAccounts = raw.entrustAccounts;
            DATA.sessionData.entrustAccounts = JSON.stringify(DATA.entrustAccounts);
            DATA.sessionData.adCampSeq = JSON.stringify(DATA.adCampSeq);
            DATA.sessionData.tagNames = JSON.stringify(DATA.tagNames);
            DATA.sessionData.isSupportInstagram='N';
            DATA.sessionData.isSupportCpa = 'N';
            for(var i=0;i<DATA.entrustAccounts.length;i++){
                if(DATA.entrustAccounts[i].supportInstagramAd){
                    DATA.sessionData.isSupportInstagram='Y';
                }

                if (DATA.entrustAccounts[i].isSupportCPA){
                    //只要有一个支持CPA就让其支持
                    DATA.sessionData.isSupportCpa = 'Y';
                }
            }
        }

        this.price = function(raw){

        }

        this.processGender = function(_conditionSex){
            if (1 == _conditionSex){
                //全部
                DATA.Gender = {
                    'GenderRenders' : {
                        0 : {
                            val: 0,
                            name: "All",
                            checked : true
                        },
                        1 : {
                            val: 1,
                            name: "Men"
                        },
                        2 : {
                            val: 2,
                            name: "Women"
                        }
                    },
                    'DefaultGender' : 0,
                    'GenderCount' : 3
                };
            } else if (2 == _conditionSex) {
                //男
                DATA.Gender = {
                    'GenderRenders': {
                        1: {
                            val: 1,
                            name: "Men",
                            checked: true
                        }
                     },
                    'DefaultGender': 1,
                    'GenderCount': 1
                };
            } else {
                //女
                DATA.Gender = {
                    'GenderRenders': {
                        2 : {
                        val: 2,
                        name: "Women",
                        checked : true
                        }
                    },
                    'DefaultGender' : 2,
                    'GenderCount' : 1
                }
            }

            DATA.sessionData.Gender = JSON.stringify(DATA.Gender);
        }

        /**
         * 初始化 DATA.temp和DATA.newTemp
         */
        this.initTempData = function(){
            console.log("初始化DATA.temp和DATA.newTemp");
            var initSetting = DATA.cache.adPublishConditionDetailCache;
            DATA.temp = {Platform:initSetting.platform,
                Age:[initSetting.age],
                Location:[{countries:[],cities:[],locationType:1}],
                CustomAudience:[{}],
                LookalikeAudience:[],
                Gender:[[DATA.Gender.DefaultGender]],
                PageTypes:[[0]],
                WirelessConnection:[[0]],
                Interests:[[]],//{id:"",name:"",locale:"en_US"}
                Behavior:[[]],
                CollegeYears:[{}],
                Connections:[{type:0,connections:[{id:DATA.app.fbConnectionObjectId,name:DATA.app.name}]}], //[{"type":0,"connections":[{"id":"40","name":"Fantasy Of Elements"}]}]
                EducationMajors:[[]],
                EducationSchools:[[]],
                EducationStatuses:[[]],
                EthnicAffinity:[[]],
                FamilyStatuses:[[]],
                Generation:[[]],
                Industries:[[]],
                Languages:[[]],
                LifeEvents:[[]],
                NewInterestedIn:[[]],
                NewRelationshipStatus:[[]],
                Politics:[[]],
                WorkEmployers:[[]],
                WorkPositions:[[]]
            };

            DATA.nowTemp = DATA.temp;
        }
    }

    return new Parse();
});
